package com.atguigu.campusintelligentassistantsystem.service;

import com.atguigu.campusintelligentassistantsystem.entity.AiChatRecord;
import com.atguigu.campusintelligentassistantsystem.repository.AiChatRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AiChatService {

    @Autowired
    private AiService aiService;

    @Autowired
    private AiChatRecordRepository aiChatRecordRepository;

    /**
     * 处理用户提问并保存聊天记录
     * @param userId 用户ID
     * @param question 用户问题
     * @return AI回答
     */
    public String processQuestion(Long userId, String question) {
        // 调用AI服务生成回答
        String answer = aiService.generateAnswer(question);

        // 保存聊天记录
        AiChatRecord record = new AiChatRecord();
        record.setUserId(userId);
        record.setQuestion(question);
        record.setAnswer(answer);
        record.setCreateTime(LocalDateTime.now());
        aiChatRecordRepository.save(record);

        return answer;
    }

    /**
     * 获取用户聊天历史记录
     * @param userId 用户ID
     * @return 聊天记录列表
     */
    public List<AiChatRecord> getChatHistory(Long userId) {
        return aiChatRecordRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    /**
     * 根据ID删除聊天记录
     * @param id 记录ID
     */
    public void deleteChatRecord(Long id) {
        aiChatRecordRepository.deleteById(id);
    }
}